<template>
  <div class="ma-content-block lg:flex justify-between p-4">
    <a-spin :loading="spinLoading" :tip="spinTip" dot style="width: 100%;">
      <a-layout-content class="flex flex-col lg:h-full relative w-full">
        <div ref="searchRef">
          <a-row v-if="showSearch" class="table-search mb-3">
            <a-col :flex="1">
              <a-form
                :model="query"
                layout="inline"
                label-align="left"
              >
                <a-row :gutter="16">
                  <a-col flex="220px">
                    <a-input v-model="query.name" placeholder="请输入名称" allow-clear>
                      <template #prepend>名称</template>
                    </a-input>
                  </a-col>
                  <a-col :span="6">
                    <a-cascader
                      v-model="query.cate_ids"
                      :options="categoryDatas"
                      :field-names="{ value: 'id', label: 'name' }"
                      :max-tag-count="1"
                      placeholder="分类"
                      multiple
                      check-strictly
                      allow-search
                      allow-clear
                      @change="pickCategoryQuery"
                    />
                  </a-col>
                  <a-col flex="360px">
                    <a-input-group>
                      <a-select v-model="query.time_type" placeholder="时间类型" :style="{width:'120px'}">
                        <a-option value="created_at" label="添加时间" />
                      </a-select>
                      <a-range-picker v-model="query.range_date" allow-clear/>
                    </a-input-group>
                  </a-col>
                </a-row>
              </a-form>
            </a-col>
            <a-col :flex="'86px'" style="text-align: right">
              <a-space :size="6">
                <a-button type="primary" @click="search">
                  <template #icon><icon-search /></template>搜索
                </a-button>
                <a-button @click="refresh()">
                  <template #icon><icon-refresh /></template>重置
                </a-button>
              </a-space>
            </a-col>
          </a-row>
        </div>
        <div class="table-header lg:flex justify-between mb-2">
          <a-space class="lg:flex block lg:inline-block">
            <a-button v-auth="['article/add']" type="primary" size="small" @click="add()">
              <template #icon><icon-plus /></template>
              <template #default>添加</template>
            </a-button>
            <a-button v-auth="['article/delete']" type="primary" status="danger" size="small" @click="batchDel()">
              <template #icon><icon-delete /></template>批量删除
            </a-button>
          </a-space>
          <a-space class="lg:mt-0 mt-2">
            <a-tooltip content="刷新表格"><a-button shape="circle" @click="refresh"><icon-refresh /></a-button></a-tooltip>
            <a-tooltip content="显隐搜索"><a-button shape="circle" @click="toggleSearch"><icon-search /></a-button></a-tooltip>
            <a-tooltip content="设置"><a-button shape="circle" @click="setTableColumns"><icon-settings /></a-button></a-tooltip>
          </a-space>
        </div>
        <div ref="tableContainerRef">
          <a-table
            ref="tableRef"
            row-key="id"
            :loading="loading"
            :pagination="pagination"
            :data="renderData"
            :bordered="{ wrapper: true, cell: true }"
            :row-selection="rowSelection"
            :scroll="tableScroll"
            column-resizable
            @selection-change="selectionChange"
            @page-change="onPageChange"
            @page-size-change="onPageSizeChange"
          >
            <template #columns>
              <vue-table-column :columns="columns">
                <template #coverImg="{ record }">
                  <a-image v-if="record.full_cover_img" :src="record.full_cover_img" width="40" height="40"/>
                </template>
                <template #name="{ record }">
                  <EditTableCell field="name" :value="record.name" :data="record" type="text" :required="true" @editTableCallback="editTableCallback" />
                </template>
                <template #description="{ record }">
                  <EditTableCell field="description" :value="record.description" :data="record" type="textarea" @editTableCallback="editTableCallback" />
                </template>
                <template #post_time="{ record }">
                  <EditTableCell field="post_time" :value="record.post_time" :data="record" type="date" :required="true" @editTableCallback="editTableCallback" />
                </template>
                <template #status="{ record }">
                  <a-tag :color="statusFilter[record.status]">{{ record.status_name }}</a-tag>
                </template>
                <template #operations="{ record }">
                  <a-space>
                    <a-dropdown>
                      <a-button type="text" size="mini">操作 <icon-down /></a-button>
                      <template #content>
                        <a-doption @click="view(record)">新窗口编辑</a-doption>
                        <a-doption v-auth="['article/edit']" @click="add(record)">编辑</a-doption>
                        <a-doption v-auth="['article/delete']" class="is-danger" @click="del([record])">删除</a-doption>
                      </template>
                    </a-dropdown>
                  </a-space>
                </template>
              </vue-table-column>
            </template>
          </a-table>
        </div>
      </a-layout-content>
    </a-spin>

    <SetColumn ref="setColumnRef" :columns="columns" @update:columns="updateColumns"/>

    <detail ref="detailRef" :categoryDatas="categoryDatas" @saveCallback="fetchData"/>
  </div>
</template>

<script setup>
  import { ref, reactive, h, compile, watch, nextTick, computed, onMounted, onUnmounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { Message, Modal } from '@arco-design/web-vue';

  import useLoading from '@/hooks/loading';
  import { workAreaHeight } from '@/utils/index';
  import tool from '@/utils/tool';
  import { apiList, apiDel, apiSave, apiCateList } from '@/api/article';
  import VueTableColumn from '@/components/table/table-column.vue';
  import SetColumn from '@/components/table/set-column.vue';
  import EditTableCell from '@/components/table/edit-table-cell.vue';
  import Detail from './components/detail.vue';

  const { loading, setLoading } = useLoading(false);
  const router = useRouter();
  const basePagination = {
    current: 1,
    pageSize: 20,
    showTotal: true,
    showJumper: true,
    showPageSize: true,
    pageSizeOptions: [10, 20, 30, 50, 100, 150, 200, 300, 500],
  };
  const baseQuery = () => {
    return {
      page: 1,
      limit: 20,
      name: '',
      cate_ids: [],
      time_type: 'created_at',
      range_date: [],
    };
  };
  const baseColumns = [
    {
      title: 'ID', dataIndex: 'id', width: 60,
      align: 'center', fixed: 'left',
      sortable: {sortDirections: ['ascend', 'descend']},
    },
    {
      title: '封面图', dataIndex: 'cover_img', width: 80,
      align: 'center',
      slotName: 'coverImg',
    },
    {
      title: '标题', dataIndex: 'name', width: 160,
      align: 'center',
      slotName: 'name',
    },
    {
      title: '分类', dataIndex: 'cate_name', width: 160,
      align: 'center',
    },
    {
      title: '网页描述', dataIndex: 'description', width: 240,
      align: 'center',
      slotName: 'description',
    },
    {
      title: '发布时间', dataIndex: 'post_time', width: 200,
      align: 'center',
      slotName: 'post_time',
    },
    {
      title: '状态', dataIndex: 'status', width: 120,
      align: 'center',
      slotName: 'status',
    },
    {
      title: '排序', dataIndex: 'sorting', width: 80,
      align: 'center',
    },
    {
      title: '创建时间', dataIndex: 'created_at', width: 180,
      align: 'center',
      sortable: {sortDirections: ['ascend', 'descend']},
    },
    {
      title: '操作', dataIndex: 'operations', width: 85,
      align: 'center', fixed: 'right',
      slotName: 'operations',
    },
  ];
  const columns = ref(tool.local.get('columns-article') || baseColumns);
  const renderData = ref([]);
  const query = ref(baseQuery());
  const pagination = reactive({
    ...basePagination,
  });
  const rowSelection = reactive({
    type: 'checkbox',
    selectedRowKeys: [],
    showCheckedAll: true,
  });
  const tableScroll = ref({
    x: '100%',
    y: '100%',
  });

  const searchRef = ref();
  const showSearch = ref(true);
  const tableContainerRef = ref();
  const tableRef = ref();
  const setColumnRef = ref();
  const searchHeight = ref(0);

  const isReset = ref(true); // 是否重置
  let selectionKeys = []; // 选中项ID
  const spinLoading = ref(false);
  const spinTip = ref();
  const detailRef = ref();

  const categoryDatas = ref([]); // 分类
  const statusFilter = {
    1: '#00b42a',
    2: '#eb0aa4',
    90: '#ff5722',
  };

  const settingFixedPage = () => {
    const workHeight = workAreaHeight();
    const tableHeight = workHeight - searchHeight.value;
    tableContainerRef.value.style.height = `${tableHeight}px`;
  };
  const resizeHandler = () => {
    searchHeight.value = searchRef.value.offsetHeight;
    settingFixedPage();
  };
  const toggleSearch = async () => {
    const dom = searchRef.value?.style;
    if (dom) {
      showSearch.value = !showSearch.value;
      await nextTick(() => {
        searchHeight.value = searchRef.value.offsetHeight;
        settingFixedPage();
      });
    }
  };
  const setTableColumns = () => {
    setColumnRef.value.init();
  };
  const updateColumns = (data) => {
    columns.value = data;
    tool.local.set('columns-article', columns.value);
  };

  // 分页
  const onPageChange = async (page) => {
    isReset.value = false;
    await fetchData({ ...query.value, page });
  };
  const onPageSizeChange = async (limit) => {
    isReset.value = false;
    await fetchData({ ...query.value, limit });
  };
  // 列表
  const fetchData = async (
    params = { ...query.value }
  ) => {
    setLoading(true);
    await reset();
    try {
      const { data } = await apiList(params);
      renderData.value = data.data;
      query.value.page = params.page;
      query.value.limit = params.limit;
      pagination.current = params.page;
      pagination.pageSize = params.limit;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 添加/编辑
  const add = (row = {}) => {
    detailRef.value.fetchData(row);
  };
  // 删除
  const del = (row) => {
    if (!row.length) {
      selectMsg();
    } else {
      let title = '删除';
      let message = `确定要删除选中的 <span style="color:red">${row.length} </span> 条数据吗？`;
      let ids = row;
      if (row.length === 1 && row[0].id) {
        title = `${title}ID：${row[0].id}`;
        message = `确定要删除 <span style="color:red">${row[0].name} </span> 这条数据吗？`;
        ids = [row[0].id];
      }
      Modal.warning({
        title,
        content: () => h('div', { innerHTML: message }),
        closable: true,
        hideCancel: false,
        onOk: (async () => {
          setLoading(true);
          try {
            await apiDel({ids});
          } catch (err) {

          } finally {
            await fetchData({...query.value});
            setLoading(false);
          }
        }),
      });
    }
  };
  // 查看
  const view = (row) => {
    router.push({
      name: 'ArticleEdit',
      // params: {
      //   id: row.id,
      // },
      query: {
        id: row.id,
      },
    });
  };
  // 重置
  const reset = async () => {
    if (isReset.value) {
      rowSelection.selectedRowKeys = [];
      selectionKeys = [];
    } else {
      isReset.value = true;
    }
  };
  // 搜索
  const search = async () => {
    query.value.page = 1;
    await fetchData({...query.value});
  };
  // 刷新
  const refresh = async () => {
    query.value = baseQuery();
    await fetchData({...query.value});
  };
  const getCategory = async () => {
    const { data } = await apiCateList();
    categoryDatas.value = data.data;
  };
  // 分类选择 -- 查询
  const pickCategoryQuery = () => {
    //
  };

  // 已选择的数据行发生改变时触发 -- table 表头
  const selectionChange = (rowKeys) => {
    rowSelection.selectedRowKeys = rowKeys;
    selectionKeys = rowKeys;
  };
  const selectMsg = (message) => {
    Message.info(message || '请选择需要操作的数据');
  };
  // 批量删除
  const batchDel = () => {
    del(selectionKeys);
  };

  // 编辑单元格回调
  const editTableCallback = async (data) => {
    await apiSave(data);
  };

  onMounted(async () => {
    await fetchData();
    await getCategory();
    window.addEventListener('resize', resizeHandler, false);
    searchHeight.value = searchRef.value.offsetHeight;
    settingFixedPage();
  });
  onUnmounted(() => {
    window.removeEventListener('resize', resizeHandler, false);
  });
</script>

<script>
  export default {
    name: 'Article',
  };
</script>

<style scoped lang="less">

</style>
